package sort;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author zhaoxingwu
 */

public class SortJson {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void sort() throws IOException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.json");
        byte[] b = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (is.read(b) > 0) {
            baos.write(b);
        }

        JsonNode jsonNode = objectMapper.readTree(baos.toByteArray());

        ArrayNode content = (ArrayNode) jsonNode.get("content");
        ObjectNode c1 = (ObjectNode) content.get(0);
        ArrayNode finish = (ArrayNode) c1.get("finishedlist");
        List<LinkedHashMap<?, ?>> list = objectMapper.convertValue(finish, List.class);
        print(list);

        System.out.println("============================================================================================");
        ArrayNode pass = (ArrayNode) c1.get("passedlist");
        List<LinkedHashMap<?, ?>> passList = objectMapper.convertValue(pass, List.class);
        print(passList);
    }


    private void print(List<LinkedHashMap<?, ?>> list) {
        list.sort((a1, a2) -> {
            try {
                ObjectNode n1 = objectMapper.readValue(objectMapper.writeValueAsString(a1), ObjectNode.class);
                ObjectNode n2 = objectMapper.readValue(objectMapper.writeValueAsString(a2), ObjectNode.class);

                long l1 = n1.get("beginTimeStamp") == null?0L:n1.get("beginTimeStamp").asLong();
                long l2 = n2.get("beginTimeStamp")==null?0L:n2.get("beginTimeStamp").asLong();
                if (l1 == l2) {
                    return 0;
                }
                return l1 > l2 ? 1 : -1;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            return 0;
        });

        list.forEach(v -> {

            long seedate = Long.parseLong(v.get("seedate").toString());
            long callmessagequeueaddtime = Long.parseLong(v.get("beginTimeStamp")==null?"0":v.get("beginTimeStamp").toString());

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            System.out.printf("%-10s %-10s %-25s %-30s \n", v.get("patientname"), v.get("serialno"), sdf.format(new Date(seedate)), sdf.format(new Date(callmessagequeueaddtime)));
        });
    }
}
